"""
Case Type   : cm_install
Case Name   : cm_install指定错误的参数
Create At   : 2025/4/16
Owner       : @ningyali
Description :
    1.配置xml文件中的cm相关参数
    2.执行cm_install,指定错误的参数
    3.cm_ctl查看集群状态
    4.gs_om查看集群状态
    5.查看数据库用户下进程和定时任务
Expect      :
    1.执行成功
    2.安装失败
    3.失败,未安装cm
    4.未安装cm
    5.无om_monitor、cm_agent、cm_server的进程，无定时任务
History     :
"""
import os
import unittest

from testcase.utils.ComInstall import CmInstall
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class CMInstallCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.root_nodes = (Node('PrimaryRoot'), Node('Standby1Root'),
                           Node('Standby2Root'))
        self.user_nodes = (Node('PrimaryDbUser'), Node('Standby1DbUser'),
                           Node('Standby2DbUser'))
        self.common = Common()
        self.constant = Constant()
        self.install_pkg_path = os.path.dirname(macro.DB_SCRIPT_PATH)
        self.cm = CmInstall(self.install_pkg_path, self.pri_sh.node.ssh_user)
        self.cm_tool_path = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), 'tool', 'tool', 'cm_tool')
        ls_cmd = f'cd {self.cm.pkg_path};ls|grep "CM"|grep "tar.gz"'
        self.log.info(ls_cmd)
        ls_res = self.common.get_sh_result(self.user_nodes[0], ls_cmd)
        self.log.info(ls_res)
        self.param = f"-X {macro.DB_XML_PATH} -e {macro.DB_ENV_PATH} " \
                     f"--cmpkg={os.path.join(self.cm.pkg_path, ls_res.strip())}"
        self.expect = {
            "-e": "[GAUSS-50001] : Incorrect parameter. Parameter "
                  "'--cmpkg' is required.",
            "--cmpkg": "[GAUSS-50000] : Unrecognized parameter: "
                       "option --cmpkgs not recognized.",
            "-X": "[GAUSS-50201] : The xmlFile does not exist.",
            "-s": "[GAUSS-50000] : Unrecognized parameter: "
                  "option -s not recognized."}

    def test_standby(self):
        text = '----step1:配置xml文件中的cm相关参数;expect:执行成功----'
        self.log.info(text)
        res = self.cm.update_xml_for_cm(*self.root_nodes)
        self.assertGreater(res.count('cmDir'), 1, f'执行失败: {text}')

        text = '----step2:执行cm_install,指定错误的参数;expect:安装失败----'
        self.log.info(text)
        for k, v in self.expect.items():
            if k != "-s":
                param = self.param.replace(k, f'{k}s')
            else:
                param = self.param + f' {k}'
            pwd = macro.COMMON_PASSWD
            install_cmd = f'''cd {self.cm_tool_path};
                        expect <<EOF
                        set timeout 1200
                        spawn ./cm_install {param}
                        expect {{{{
                            "*ca cert*" {{{{ send "{pwd}\\n"; exp_continue }}}}
                            "*ca cert*" {{{{ send "{pwd}\\n" }}}}
                            eof
                        }}}}''' + '\nEOF'
            install_res = self.common.get_sh_result(
                self.user_nodes[0], install_cmd)
            self.assertIn(v, install_res, '执行失败:' + text)

        text = '----step3:cm_ctl查看集群状态;expect:失败,未安装cm----'
        self.log.info(text)
        show_status = f'source {macro.DB_ENV_PATH};' \
                      f'cm_ctl query -Civdp'
        status_msg = self.common.get_sh_result(self.user_nodes[0], show_status)
        self.assertIn("cm_ctl: command not found", status_msg, "执行失败:" + text)

        text = '----step4:gs_om查看集群状态;expect:未安装cm----'
        self.log.info(text)
        status_msg = self.pri_sh.get_db_cluster_status('detail')
        self.log.info(status_msg)
        self.assertNotIn('CMServer State', status_msg, "执行失败:" + text)

        text = '----step5:查看数据库用户下进程和定时任务;' \
               'expect:无om_monitor、cm_agent、cm_server的进程，无定时任务----'
        self.log.info(text)
        show_cmd = "crontab -l;ps ux|egrep 'cm_server|cm_agent|om_monitor';"
        process_res = self.pri_sh.exec_gs_ssh(show_cmd)
        self.assertNotIn(process_res, 'bin/cm_server', "执行失败:" + text)
        self.assertNotIn(process_res, 'bin/cm_agent', "执行失败:" + text)
        self.assertNotIn(process_res, 'om_monitor -L', "执行失败:" + text)

    def tearDown(self):
        text = '----poststep1:还原xml;expect:执行成功----'
        self.log.info(text)
        sed_cmd = f'sed -i \'/cm/d\' {self.cm.xml_path};'
        sed_res = self.common.get_sh_result(self.user_nodes[0], sed_cmd)
        self.assertNotIn('error', sed_res.lower(), "执行失败:" + text)
        self.log.info(f'----{os.path.basename(__file__)} end----')
